<template>
  <type-wrapper :name="name">
    <div class="member-container">
      <div class="member-item" v-for="(member, memberIndex) in extra.selectedValue" :key="memberIndex">
        <div class="options-item" v-for="(key, index) in Object.keys(member)" :key="index">
          <options-container
            style="flex:1;"
            :type="config[key].type"
            :name="config[key].name"
            :extra="{...config[key].extra, selectedValue: extra.selectedValue[memberIndex][key]}"
            :config="config[key].config"
            @change="(e) => onChange(e, memberIndex, key)"
          />
        </div>
        <el-button
          size="small"
          type="danger"
          class="btn delete-btn"
          @click="onDeleteBtnClick(memberIndex)"
        >-</el-button>
      </div>
      <div class="button-group">
        <el-button
          size="small"
          type="plain"
          class="btn add-btn"
          @click="onAddBtnClick"
        >+</el-button>
      </div>
    </div>
  </type-wrapper>
</template>

<script>
import { Button } from 'element-ui'
import TypeWrapper from './type-wrapper.vue'
function deepClone(value) {
  return JSON.parse(JSON.stringify(value))
}

export default {
  name: 'type-array',
  components: {
    'type-wrapper': TypeWrapper,
    'el-button': Button,
  },
  data() {
    return {
      forCreateItem: null
    }
  },
  props: {
    name: {
      type: String,
    },
    config: {
      type: Object,
    },
    extra: {
      type: Object,
    }
  },
  watch: {
    extra: {
      immediate: true,
      handler(extra) {
        if (!this.forCreateItem && extra.selectedValue) {
          this.forCreateItem = deepClone(extra.selectedValue[0])
        }
      }
    }
  },
  methods: {
    onChange(res, memberIndex, key) {
      const newSelectedValue = deepClone(this.extra.selectedValue)
      newSelectedValue[memberIndex][key] = res
      this.$emit('change', newSelectedValue)
    },
    onAddBtnClick() {
      const newSelectedValue = [
        ...this.extra.selectedValue,
        deepClone(this.forCreateItem)
      ]
      this.$emit('change', newSelectedValue)
    },
    onDeleteBtnClick(memberIndex) {
      const teek = (_, idx) => idx !== memberIndex
      const newSelectedValue = this.extra.selectedValue.filter(teek)
      this.$emit('change', newSelectedValue)
    }
  }
}
</script>

<style scoped>
.member-item{
  margin-bottom: 20px;
  border: 1px solid #eee;
  padding: 15px 10px;
}
.delete-btn{
  width: 100%;
}
.options-item{
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 10px;
}
.button-group{
  display: flex;
  align-items: center;
  justify-content: center;
}
.btn{
  flex: 1;
}
</style>